package org.sky.image.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.sky.image.common.pojo.Pages;
import org.sky.image.common.pojo.Result;
import org.sky.image.common.utils.CommonUtils;
import org.sky.image.common.utils.ImgUtils;
import org.sky.image.dao.ImageDao;
import org.sky.image.pojo.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Date: 2019/3/4 15:06
 * @Description: 菜品图片分类
 */
@Service
public class ImageService {


    @Autowired
    private ImageDao imageDao;


    @Value("${upload.path}")
    private String uploadPath;


    @Value("${upload.temp}")
    private String uploadTemp;


    @Value("${upload.url}")
    private String uploadUrl;


    /**
     * 保存修改图片
     * @param image
     * @return
     */
    @Transactional
    public ResponseEntity<Result> saveOrUpdateImage(Image image) {
        String imageStr = image.getImages();
        String[] imgs = imageStr.split(",");
        StringBuilder sb = new StringBuilder();
        String code = image.getCode();
        for (String img : imgs) {
            if (StringUtils.isNotBlank(img)) {
                String newImg = img.substring(img.lastIndexOf("-"), img.length());
                sb.append(uploadUrl + code + newImg).append(",");
            }
        }
        image.setImages(sb.toString());
        if (null == image.getId()) {
            Image i = new Image();
            i.setTypeName(image.getTypeName());
            List<Image> imageList = this.imageDao.select(i);
            if (!imageList.isEmpty()) {
                return ResponseEntity.badRequest().body(Result.msg(1, "分类名称已存在！"));
            }
            this.imageDao.insertSelective(image);
        } else {
            this.imageDao.updateByPrimaryKeySelective(image);
        }
        return ResponseEntity.ok(Result.successMsg());
    }


    /**
     * 删除图片
     * @param id
     * @return
     */
    @Transactional
    public ResponseEntity<Result> deleteImage(Integer id) {
        // 删除图片
        Image image = this.imageDao.selectByPrimaryKey(id);
        if (image != null) {
            String images = image.getImages();
            String[] strings = images.split(",");
            for (String img : strings) {
                if (StringUtils.isNotBlank(img)) {
                    String s = img.replace(uploadUrl, "");
                    File oldFile = new File(uploadPath + s);
                    oldFile.delete();
                }
            }
            this.imageDao.deleteByPrimaryKey(id);
        }
        return ResponseEntity.ok(Result.successMsg());
    }


    /**
     * 查询图片
     * @param image
     * @return
     */
    public ResponseEntity<Result> selectImage(Image image, Pages pages) {
        Page<Object> objectPage = PageHelper.startPage(pages.getPage(), pages.getLimit());
        List<Image> images = this.imageDao.selectAll();
        return ResponseEntity.ok(Result.data(0, objectPage.getTotal(), images));
    }


    /**
     * 识别图片信息
     * @param file
     * @return
     */
    public ResponseEntity<Result> discernImage(MultipartFile file, Integer id) throws IOException {
        double similarity1, similarity2, similarity3;
        String fileName1 = null, fileName2 = null, fileName3 = null;
        String fileSuffix = CommonUtils.getFileSuffix(file.getOriginalFilename());
        String fileName = CommonUtils.getKey();
        fileName = fileName + fileSuffix;
        File tmpFolder = new File(uploadTemp);
        if (!tmpFolder.exists()) {
            tmpFolder.mkdirs();
        }
        File tmpFile = new File(uploadTemp + fileName);
        // 保存需要识别的图片
        file.transferTo(tmpFile);
        File folder = new File(uploadPath);
        File[] files = folder.listFiles();
        if (files.length < 3) {
            Result result = new Result(1, "图片库暂无数据！");
            result.setCode(1);
            return ResponseEntity.ok(result);
        }
        // 遍历进行匹配，匹配出相似度最高的三个
        similarity1 = ImgUtils.getSimilarity(tmpFile, files[0]);
        similarity2 = ImgUtils.getSimilarity(tmpFile, files[1]);
        similarity3 = ImgUtils.getSimilarity(tmpFile, files[2]);
        fileName1 = files[0].getName();
        fileName2 = files[1].getName();
        fileName3 = files[2].getName();
        for (int i = 3; i < files.length; i++) {
            double similarity;
            String name = files[i].getName();
            similarity = ImgUtils.getSimilarity(tmpFile, files[i]);
            if (similarity1 < similarity && similarity != similarity2 && similarity != similarity3) {
                similarity1 = similarity;
                fileName1 = name;
            } else if (similarity2 < similarity && similarity != similarity1 && similarity != similarity3) {
                similarity2 = similarity;
                fileName2 = name;
            } else if (similarity3 < similarity && similarity != similarity1 && similarity != similarity2) {
                similarity3 = similarity;
                fileName3 = name;
            }
        }
        String[] ids = new String[3];
        ids[0] = fileName1.substring(0, fileName1.lastIndexOf("-"));
        ids[1] = fileName2.substring(0, fileName2.lastIndexOf("-"));
        ids[2] = fileName3.substring(0, fileName3.lastIndexOf("-"));
        Example example = new Example(Image.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("code", Arrays.asList(ids));
        // 只查4条
        PageHelper.startPage(1, 4);
        List<Image> imageList = this.imageDao.selectByExample(example);
        return ResponseEntity.ok(Result.data(0, imageList));
    }

}
